package org.six11.olive3.server;

import static org.six11.olive3.server.WebActionServlet.SESSION_USER_ID;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.six11.util2.Debug;

/**
 * 
 *
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class BrowseHandler extends WebActionHandler {

  /**
   * @param jspPage
   * @param webActionServlet
   */
  public BrowseHandler(String jspPage, WebActionServlet webActionServlet) {
    super(jspPage, webActionServlet);
  }

  /**
   * 
   */
  @Override
  public void service(HttpServletRequest req, HttpServletResponse resp, ServletContext context)
      throws ServletException, IOException {
    
    String suid = (String) req.getSession().getAttribute(SESSION_USER_ID);
    String sketchID = req.getParameter(WebActionServlet.PARAM_SKETCH_ID);
    String descID = req.getParameter(WebActionServlet.PARAM_DESC_ID);
    String userID = req.getParameter(WebActionServlet.PARAM_USER);
    
    if (sketchID != null || descID != null) {
      String type = (sketchID == null) ? DrillData.TYPE_DESC : DrillData.TYPE_SKETCH;
      String targetID = (sketchID == null) ? descID : sketchID;
      
      List<DrillData> data = DrillData.getLineage(webActionServlet.dbThing, type, targetID);
      List<DrillData> leaves = DrillData.getLeaves(webActionServlet.dbThing, type, targetID);
      
      req.setAttribute("drillData", data);
      req.setAttribute("leaves", leaves);
      go(req, resp, context);

    } else {
      List<DrillData> data = DrillData.getPeruse(webActionServlet.dbThing); 
      req.setAttribute("drillData", data);
      forwardTo("/peruse.jsp", req, resp, context);
    }
  }

  private void bug(String what) {
    Debug.out("BrowseHandler", what);
  }

}
